﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using XsClient.Common;

namespace XsClient.Parsers
{
    /// <summary>
    /// 顶点小说解析
    /// </summary>
    class DingdianResolver : BaseResolver
    {

        public override XsSource Source { get => base.Source; protected set => base.Source = value; }

        protected override string listRegex => @"<li><a\s+href=(?<url>.+?)>(?<content>.+?)</a>(?<content>.+?)</li>";

        protected override string chaperRegex => @"<dd><a\s+href=(?<url>.+?)>(?<content>.+?)</a></dd>";
        /// <summary>
        /// 内容
        /// </summary>
        protected override string contextRegex => "<div id=\"content\">";
        /// <summary>
        /// url
        /// </summary>
        private string bookUrlRegex = "http://[^\\s]*\"";
        /// <summary>
        /// 名称
        /// </summary>
        private string nameRegex = "\">[^\\s]*</a>";

        private string authorRegex = "著[^\\s]*</li>";

        Regex listRx = null;
        Regex chaperRx = null;

        Regex bookRx = null;
        Regex nameRx = null;
        Regex authorRx = null;
        Regex chaperNameRx = null;
        Regex chaperUrlRx = null;

        private string bgqtemp = "window.location=";
        const string baseUrl = "http://www.dingdianxs.la/";
        public DingdianResolver()
        {
            InitSource(3, new XsSource() { BaseUrl = baseUrl, Encoding = "utf8", ID = 3, Name = "顶点小说" });
            
            seachUrl = Source.BaseUrl + "modules/article/search.php?searchkey={0}";
            listRx = new Regex(listRegex);
            chaperRx = new Regex(chaperRegex);
            bookRx = new Regex(bookUrlRegex);
            nameRx = new Regex(nameRegex);
            authorRx = new Regex(authorRegex);
            chaperUrlRx = new Regex("href=[^\\s]*html");
            chaperNameRx = new Regex("title=[^\\\\s]*\">");
        }
        public override List<BookInfo> Seach(string name)
        {
            string url = string.Format(seachUrl, HttpUtility.UrlEncode(name));
            string htmlStr = Client.GetHtml(url, Source.Encoding);
            return base.Seach(name);
        }
        public override List<BookInfo> FindBooks(string url)
        {
            return base.FindBooks(url);
        }
        public override List<BookInfo> FindBooksByHtml(string html)
        {
            if (html.Contains(bgqtemp))
            {
                string tempkey = html.Substring(html.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                html = Client.GetHtml(baseUrl + tempkey, Source.Encoding);

            }
            var collection = listRx.Matches(html);
            if (collection != null && collection.Count > 0)
            {
                List<BookInfo> books = new List<BookInfo>();
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string url = bookRx.Match(value).Value.Trim('"');
                        string name = nameRx.Match(value).Value.Substring(2).Replace("</a>", "");
                        string author = authorRx.Match(value).Value.Substring(2).Replace("</li>", "");
                        BookInfo info = new BookInfo()
                        {
                            BaseUrl = url,
                            Name = name,
                            Author = author,
                            SourceID = Source.ID
                        };

                        books.Add(info);
                    }
                    catch (Exception ex)
                    {
                        NewLife.Log.XTrace.WriteException(ex);
                    }
                }
                return books;
            }
            return null;
        }

        public override List<ChaperInfo> FindChapers(ref string url)
        {
            string bookUrl = url;
            string htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            if (htmlStr == null)
                return null;
            if (htmlStr.Contains(bgqtemp))
            {
                string tempkey = htmlStr.Substring(htmlStr.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                bookUrl = Source.BaseUrl + tempkey;
                htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            }
            GetBaseUrl(bookUrl);
            url = bookUrl;

            var collection = chaperRx.Matches(htmlStr);
            if (collection != null && collection.Count > 0)
            {
                List<ChaperInfo> chapers = new List<ChaperInfo>();
                int i = 0;
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string itemUrl = chaperUrlRx.Match(value).Value.Substring(6);
                        string name = chaperNameRx.Match(value).Value.Substring(7).Replace("\">", "");
                        ChaperInfo chaper = new ChaperInfo() { ID = i++, Url = url.TrimEnd('/') + "/" + itemUrl, Name = name };
                        chaper.SourceID = Source.ID;
                        chapers.Add(chaper);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                }
                return chapers;
            }
            return null;
        }

        public override string GetContext(string url)
        {
            string htmlStr = Client.GetHtml(url, Source.Encoding);

            int startIndex = htmlStr.IndexOf(contextRegex);
            if (startIndex > 0)
            {
                int endIndex = htmlStr.IndexOf("<!--over-->", startIndex + 27);

                return htmlStr.Substring(startIndex + 27, endIndex - startIndex - 27).Replace("<br/>", "\r\n").Replace("&nbsp;", " ");
            }

            return null;
        }
    }
}
